package com.example.redistokendemo.controller;

import com.example.redistokendemo.annotation.ApiIdempotent;
import com.example.redistokendemo.bean.User;
import com.example.redistokendemo.utils.RedisUtil;
import com.example.redistokendemo.utils.TokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-11 21:28
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisUtil redisUtil;

    @ApiIdempotent
    @GetMapping(value = "/getUser")
    public User getUser() throws IOException {
        User user = User.builder()
                .address("北京朝阳111")
                .age(27)
                .birthday(new Date())
                .name("王华军222").build();
        User user2 = User.builder()
                .address("上海")
                .age(24)
                .name("六").build();
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(user);


        List<User> list = new ArrayList<>();
        list.add(user);
        list.add(user2);
        boolean listuser = redisUtil.set("listuser", list);
        log.info("listuser------->{}", listuser);

        List<User> listuser1 = (List<User>) redisUtil.get("listuser");
        log.info("list------------>{},size:{}", listuser1, listuser1.size());
        for (User u : listuser1) {
            log.info(u.getName());
            log.info("{}", u.getBirthday());
            log.info("==========");
            // log.info("o------->{}",o);
        }

        redisUtil.set("user", s);

        User user1 = mapper.readValue((String) redisUtil.get("user"), User.class);

        return user1;
    }

    @GetMapping(value = "/token")
    public String getToken() {
        return tokenUtil.createToken();
    }

    @GetMapping(value = "getToken")
    public String getToken(String token) {
        log.info("token------->{}", token);
        String s = (String) redisUtil.get(token);
        log.info("redis值-------->{}", s);
        return s;
    }

}
